package weatherstation;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import settings.Settings;
import utilities.ANSI;

/**
 * The Class WeatherStationQueueHandler.
 * 
 * @author Nils Berlijn
 * @author Henderikus Harms
 * @version 1.0
 * @since June 1, 2014
 */
public class WeatherStationQueueHandler implements Runnable
{
	/** The weather station queue. */
	private WeatherStationQueue<Runnable> weatherStationQueue;
	
	/** The fixed thread pool. */
	private ExecutorService fixedThreadPool;	
	
	/** The listen. */
	private boolean listen;

	/**
	 * Instantiates a new weather station queue handler.
	 *
	 * @param threadPoolSize the thread pool size
	 * @param weatherStationQueue the weather station queue
	 */
	public WeatherStationQueueHandler(int threadPoolSize, WeatherStationQueue<Runnable> weatherStationQueue)
	{
		try 
		{	
			System.out.println(ANSI.GREEN + "Weather Station Queue Handler is successfully launched." + ANSI.NORMAL);

			this.weatherStationQueue = weatherStationQueue;
			this.fixedThreadPool = Executors.newFixedThreadPool(threadPoolSize);			
			this.listen = true;
			
			System.out.println(ANSI.YELLOW + "Weather Station Queue Handler is waiting for incoming data...\n" + ANSI.NORMAL);
		} 
		catch(Exception e) 
		{
			this.listen = false;
			
			System.out.println(ANSI.RED + "Weather Station Queue Handler is not successfully launched!\n" + ANSI.NORMAL);			
		}
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run()
	{		
		while(listen == true)
		{
			try 
			{
				Runnable runnable = weatherStationQueue.remove();
				WeatherStationWorker weatherStationWorker = (WeatherStationWorker)runnable;

				fixedThreadPool.execute(runnable);
				
				System.out.println(ANSI.BLUE + "Weather Station Queue Handler: " + ANSI.YELLOW + "\"" + weatherStationWorker.weatherStationWorkerSocket() + "\" has been added to the Thread Pool" + ANSI.NORMAL);	 			

				Thread.sleep(Settings.WEATHER_STATION_QUEUE_THREAD_SLEEP_TIME);	
			} 
			catch (InterruptedException e) 
			{
				
			}
		}
	}
}